<template>
  <el-row :gutter="24">
    <el-col :span="16">
      <ContentWrap title="申请信息">
        <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="160px">
          <el-row :gutter="20">
            <!-- 项目及公司信息分组 -->
            <el-tag type="info" style="width: 100%;height: 30px;margin-bottom: 20px;">
              <h3>项目及公司信息</h3>
            </el-tag>
            
            <!-- 左侧列 -->
            <el-col :span="12">
              <el-form-item label="项目编号" prop="projectNumber">
                <el-input v-model="formData.projectNumber" placeholder="自动生成,创建后可见" :disabled="true" />
              </el-form-item>
              <el-form-item label="项目类型" prop="projectType">
                <el-checkbox-group v-model="formData.projectType">
                  <el-checkbox
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_PROJECT_TYPE)" 
                    :key="dict.value"
                    :label="dict.label" 
                    :value="dict.value" 
                  />
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="是否计算项目数" prop="isCountedProject">
                <el-radio-group v-model="formData.isCountedProject">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_IS_OR_NO)" 
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否为重点企业" prop="isKeyEnterprise">
                <el-radio-group v-model="formData.isKeyEnterprise">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_IS_OR_NO)" 
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="税收情况" prop="taxSituation">
                <el-input v-model="formData.taxSituation" placeholder="请输入税收情况" />
              </el-form-item>
            </el-col>

            <!-- 右侧列 -->
            <el-col :span="12">
              <el-form-item label="公司名称" prop="companyName">
                <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
              </el-form-item>
              <el-form-item label="注册园区及平台" prop="registeredParkPlatform">
                <el-input v-model="formData.registeredParkPlatform" placeholder="请输入注册园区及平台" />
              </el-form-item>
              <el-form-item label="纳税人属性" prop="taxpayerAttribute">
                <el-select v-model="formData.taxpayerAttribute" placeholder="请选择纳税人属性" class="!w-full">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_TAXPAYER_ATTRIBUTE)" 
                    :key="dict.value"
                    :label="dict.label" 
                    :value="dict.value" 
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="介绍人或下级平台" prop="introducerOrSubPlatform" class="no-wrap-label">
                <el-input v-model="formData.introducerOrSubPlatform" placeholder="请输入介绍人或下级平台" />
              </el-form-item>
            </el-col>

            <!-- 联系人信息分组 -->
            <el-tag type="info" style="width: 100%;height: 30px;margin-bottom: 20px;">
              <h3>联系人信息</h3>
            </el-tag>
            
            <el-col :span="12">
              <el-form-item label="法定代表人" prop="legalPerson">
                <el-input v-model="formData.legalPerson" placeholder="请输入法人姓名" />
              </el-form-item>
              
            </el-col>
            <el-col :span="12">
              <el-form-item label="法人电话" prop="legalPersonPhone">
                <el-input v-model="formData.legalPersonPhone" placeholder="请输入法人实名电话号码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业联系人" prop="enterpriseContact">
                <el-input v-model="formData.enterpriseContact" placeholder="请输入企业联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业电话" prop="enterpriseContactPhone">
                <el-input v-model="formData.enterpriseContactPhone" placeholder="请输入企业联系人电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="招商负责人" prop="investmentPromotionOfficer">
                <el-input v-model="formData.investmentPromotionOfficer" placeholder="请输入招商负责人" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="项目确认人" prop="registrantId">
                <UserSelect 
                  :user-id="formData.registrantId" 
                  @node-change="handleRegistrantChange" 
                />
              </el-form-item>
            </el-col> -->
            

            <!-- 项目详细信息分组 -->
            <el-tag type="info" style="width: 100%;height: 30px;margin-bottom: 20px;">
              <h3>项目详细信息</h3>
            </el-tag>
            
            <el-col :span="12">
              <el-form-item label="返税比例" prop="taxRefundRatio">
                <el-input v-model="formData.taxRefundRatio" placeholder="请输入返税比例" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="记账收费价格/月" prop="serviceFee">
                <el-input-number v-model="formData.serviceFee" :precision="0" :step="50"  />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目引进说明" prop="remark">
                <el-input 
                  v-model="formData.remark" 
                  type="textarea" 
                  :rows="4"
                  placeholder="请输入项目引进情况说明" 
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 表单底部按钮 -->
          <el-form-item>
            <el-button
              type="success" 
              :loading="saveLoading" 
              @click="saveForm"
              v-hasPermi="['oa:project-management:create']"
            >
              保存
            </el-button>
            <el-button
              type="primary" 
              :loading="submitLoading" 
              @click="submitForm"
              v-hasPermi="['oa:project-management:create']"
            >
              提交
            </el-button>
            <el-button @click="onCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
    </el-col>

    <!-- 审批相关：流程信息 -->
    <el-col :span="6">
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline
          ref="timelineRef" 
          :activity-nodes="activityNodes" 
          :show-status-icon="false"
          @select-user-confirm="selectUserConfirm" 
        />
      </ContentWrap>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ProjectManagementApi, ProjectManagementVO } from '@/api/oa/projectmanagement'
import { useTagsViewStore } from '@/store/modules/tagsView'
import UserSelect from '@/views/system/user/UserSelect.vue'

// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'

defineOptions({ name: 'OaProjectManagementCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const saveLoading = ref(false) // 保存按钮的加载中
const submitLoading = ref(false) // 提交按钮的加载中
const formData = ref({
  id: undefined,
  projectNumber: undefined,
  projectType: [],
  legalPerson: undefined,
  enterpriseContact: undefined,
  taxpayerAttribute: undefined,
  investmentPromotionOfficer: undefined,
  registrantId: undefined,
  registrantName: undefined,
  isCountedProject: undefined,
  taxSituation: undefined,
  isSimplifiedEnterprise: undefined,
  isKeyEnterprise: undefined,
  taxRefundRatio: undefined,
  companyName: undefined,
  registeredParkPlatform: undefined,
  legalPersonPhone: undefined,
  enterpriseContactPhone: undefined,
  serviceFee: undefined,
  introducerOrSubPlatform: undefined,
  status: undefined,
  processInstanceId: undefined,
  projectStatus: 1, // 默认项目状态为待办理
  remark: undefined,
})
const formRules = reactive({
  // projectNumber: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
  projectType: [{ required: true, message: '项目类型不能为空', trigger: 'change' }],
  isCountedProject: [{ required: true, message: '是否计算项目数不能为空', trigger: 'change' }],
  isKeyEnterprise: [{ required: true, message: '是否为重点企业不能为空', trigger: 'change' }],
  taxpayerAttribute: [{ required: true, message: '纳税人属性不能为空', trigger: 'change' }],
  taxSituation: [{ required: true, message: '税收情况不能为空', trigger: 'blur' }],
  investmentPromotionOfficer: [{ required: true, message: '招商负责人不能为空', trigger: 'blur' }],
  // registrantId: [{ required: true, message: '项目确认人不能为空', trigger: 'change' }],
  serviceFee: [{ required: true, message: '记账收费价格不能为空', trigger: 'blur' }],
  companyName: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  registeredParkPlatform: [{ required: true, message: '注册园区及平台不能为空', trigger: 'blur' }],
  legalPerson: [{ required: true, message: '法定代表人不能为空', trigger: 'blur' }],
  legalPersonPhone: [{ required: true, message: '法人电话号码不能为空', trigger: 'blur' }],
  enterpriseContact: [{ required: true, message: '企业联系人不能为空', trigger: 'blur' }],
  enterpriseContactPhone: [{ required: true, message: '企业联系人电话不能为空', trigger: 'blur' }],
  introducerOrSubPlatform: [{ required: true, message: '介绍人或下级平台不能为空', trigger: 'blur' }],
  taxRefundRatio: [{ required: true, message: '返税比例不能为空', trigger: 'blur' }],
  remark: [{ required: true, message: '项目引进情况说明不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '审批结果不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

// 审批相关：变量
const processDefineKey = 'oa_project_management' // 流程定义 Key
const startUserSelectTasks = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<Record<string, number[]>>({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref<Record<string, number[]>>({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')

/** 保存表单（只入库，不提交流程） */
const saveForm = async () => {
  // 1.1 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 2. 保存请求
  saveLoading.value = true
  try {
    //设置默认的 项目确认人
    formData.value.registrantId = 163
    formData.value.registrantName = "张晓倩"
    const data = { ...formData.value } as unknown as ProjectManagementVO
    // 将项目类型数组转换为逗号分隔的字符串
    if (Array.isArray(data.projectType)) {
      data.projectType = data.projectType.join(',')
    }
    
    if (data.id) {
      // 存在ID，执行更新
      await ProjectManagementApi.updateProjectManagement(data)
      message.success('保存成功')
    } else {
      // 不存在ID，执行新增
      await ProjectManagementApi.saveProjectManagement(data)
      message.success('保存成功')
    }
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'ProjectManagementOwner' })
  } finally {
    saveLoading.value = false
  }
}

/** 提交表单（入库并提交流程） */
const submitForm = async () => {
  // 1.1 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 1.2 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id]) &&
        startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择\${userTask.name}的审批人`)
      }
    }
  }

  // 2. 提交请求
  submitLoading.value = true
  try {
    //设置默认的 项目确认人
    formData.value.registrantId = 163
    formData.value.registrantName = "张晓倩"
    const data = { ...formData.value } as unknown as ProjectManagementVO
    // 将项目类型数组转换为逗号分隔的字符串
    if (Array.isArray(data.projectType)) {
      data.projectType = data.projectType.join(',')
    }
    // 审批相关：设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
      // 将 Record 转换为 Map
      const assigneesMap = new Map<string, number[]>()
      Object.entries(startUserSelectAssignees.value).forEach(([key, value]) => {
        assigneesMap.set(key, value)
      })
      data.startUserSelectAssignees = assigneesMap
    }
    
    if (data.id) {
      // 存在ID，执行更新并提交流程
      await ProjectManagementApi.submitProjectManagement(data)
      message.success('提交成功')
    } else {
      // 不存在ID，执行新增并提交流程
      await ProjectManagementApi.createProjectManagement(data)
      message.success('发起成功')
    }
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'ProjectManagementOwner' })
  } finally {
    submitLoading.value = false
  }
}

/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      // TODO 小北：可以支持 processDefinitionKey 查询
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: JSON.stringify({ day: daysDifference() }) // 解决 GET 无法传递对象的问题，后端 String 再转 JSON
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {
  }
}

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

/** 处理注册人选择 */
const handleRegistrantChange = (user: any) => {
  console.log(user)
  if (user) {
    formData.value.registrantId = user.id
    formData.value.registrantName = user.nickname
  } else {
    formData.value.registrantId = undefined
    formData.value.registrantName = undefined
  }
}

// 计算天数差
// TODO @小北：可以搞到 formatTime 里面去，然后看看 dayjs 里面有没有现成的方法，或者辅助计算的方法。
const daysDifference = () => {
  // 由于项目管理表单没有时间字段，这里返回默认值
  return 1
}

/** 初始化 */
onMounted(async () => {
  // TODO @小北：这里可以简化，统一通过 getApprovalDetail 处理么？
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )

  if (!processDefinitionDetail) {
    message.error('项目管理的流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail()
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次, formData.value可改成实际业务中的特定字段 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    if (newValue && Object.keys(newValue).length > 0) {
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: true
  }
)

/** 取消按钮事件 */
const onCancel = () => {
  delView(unref(currentRoute))
  push({ name: 'ProjectManagement' })
}
</script>

<style scoped>
.no-wrap-label .el-form-item__label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
